import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { 
  Card, 
  Form, 
  Input, 
  Button, 
  Select, 
  message, 
  Space, 
  Typography, 
  Divider,
  Row,
  Col,
  Alert,
  Tag,
  Table,
  Modal,
  Progress,
  Tooltip
} from 'antd';
import { 
  SafetyCertificateOutlined,
  LockOutlined,
  CreditCardOutlined,
  UserOutlined,
  EyeOutlined,
  EyeInvisibleOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  SecurityScanOutlined
} from '@ant-design/icons';
import * as customerController from '@/services/backend/customerController';

const { Title, Text, Paragraph } = Typography;
const { Option } = Select;
const { Password } = Input;

const Security: React.FC = () => {
  const [cardForm] = Form.useForm();
  const [userForm] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [cards, setCards] = useState<any[]>([]);
  const [securityLevel, setSecurityLevel] = useState(85);

  // 模拟银行卡数据
  const mockCards = [
    { cardId: '6222021234567890123', balance: 15000, status: 1, lastPasswordChange: '2024-01-01' },
    { cardId: '6222021234567890124', balance: 8000, status: 1, lastPasswordChange: '2024-01-10' },
  ];

  useEffect(() => {
    setCards(mockCards);
  }, []);

  // 修改银行卡密码
  const handleCardPasswordChange = async (values: any) => {
    if (values.newPassword !== values.confirmPassword) {
      message.error('两次输入的新密码不一致');
      return;
    }

    setLoading(true);
    try {
      await customerController.updateCardPassword(values.cardId, {
        old_password: values.oldPassword,
        new_password: values.newPassword
      });
      message.success('银行卡密码修改成功！');
      cardForm.resetFields();
      
      // 更新最后修改时间
      setCards(prev => prev.map(card => 
        card.cardId === values.cardId 
          ? { ...card, lastPasswordChange: new Date().toISOString().split('T')[0] }
          : card
      ));
    } catch (error) {
      message.error('密码修改失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 修改用户账户密码
  const handleUserPasswordChange = async (values: any) => {
    if (values.newPassword !== values.confirmPassword) {
      message.error('两次输入的新密码不一致');
      return;
    }

    setLoading(true);
    try {
      await customerController.updateUserPassword({
        old_password: values.oldPassword,
        new_password: values.newPassword
      });
      message.success('账户密码修改成功！');
      userForm.resetFields();
    } catch (error) {
      message.error('密码修改失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 银行卡挂失/解挂
  const handleCardReportLoss = async (cardId: string, isReportLoss: boolean) => {
    Modal.confirm({
      title: isReportLoss ? '确认挂失' : '确认解挂',
      content: isReportLoss 
        ? '挂失后该银行卡将无法进行交易，确定要挂失吗？'
        : '解挂后该银行卡将恢复正常使用，确定要解挂吗？',
      onOk: async () => {
        try {
          await customerController.reportCardLoss(cardId, { pid: '123456789012345678' });
          message.success(isReportLoss ? '挂失成功！' : '解挂成功！');
          // 更新卡片状态
          setCards(prev => prev.map(card => 
            card.cardId === cardId 
              ? { ...card, isReportLoss: isReportLoss ? 1 : 0 }
              : card
          ));
        } catch (error) {
          message.error('操作失败，请重试');
        }
      }
    });
  };

  // 密码强度检查
  const checkPasswordStrength = (password: string) => {
    let score = 0;
    if (password.length >= 8) score += 25;
    if (/[a-z]/.test(password)) score += 25;
    if (/[A-Z]/.test(password)) score += 25;
    if (/[0-9]/.test(password)) score += 25;
    return score;
  };

  // 银行卡列表列定义
  const cardColumns = [
    {
      title: '银行卡号',
      dataIndex: 'cardId',
      key: 'cardId',
      render: (cardId: string) => (
        <Space>
          <CreditCardOutlined style={{ color: '#1890ff' }} />
          <Text code>{cardId}</Text>
        </Space>
      )
    },
    {
      title: '余额',
      dataIndex: 'balance',
      key: 'balance',
      render: (balance: number) => `¥${balance.toLocaleString()}`
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: number, record: any) => {
        if (record.isReportLoss) {
          return <Tag color="red">已挂失</Tag>;
        }
        return status === 1 ? <Tag color="green">正常</Tag> : <Tag color="orange">异常</Tag>;
      }
    },
    {
      title: '最后密码修改',
      dataIndex: 'lastPasswordChange',
      key: 'lastPasswordChange',
      render: (date: string) => date || '未修改'
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: any) => (
        <Space>
          <Button 
            type="link" 
            size="small"
            onClick={() => {
              cardForm.setFieldsValue({ cardId: record.cardId });
              Modal.info({
                title: '修改银行卡密码',
                content: '请在下方表单中修改密码',
                onOk: () => {
                  // 可以在这里添加跳转到密码修改表单的逻辑
                }
              });
            }}
          >
            修改密码
          </Button>
          <Button 
            type="link" 
            size="small"
            danger={!record.isReportLoss}
            onClick={() => handleCardReportLoss(record.cardId, !record.isReportLoss)}
          >
            {record.isReportLoss ? '解挂' : '挂失'}
          </Button>
        </Space>
      )
    }
  ];

  return (
    <PageContainer>
      <div style={{ marginBottom: '24px' }}>
        <Title level={2}>
          <SafetyCertificateOutlined style={{ marginRight: '8px', color: '#1890ff' }} />
          卡片安全
        </Title>
        <Text type="secondary">
          管理您的银行卡密码、账户密码和安全设置
        </Text>
      </div>

      <Alert
        message="安全提醒"
        description="请定期修改密码，不要在公共场所输入密码，确保账户安全。"
        type="warning"
        showIcon
        style={{ marginBottom: '24px' }}
      />

      <Row gutter={[24, 24]}>
        {/* 安全等级 */}
        <Col xs={24} lg={8}>
          <Card 
            title={
              <Space>
                <SecurityScanOutlined style={{ color: '#52c41a' }} />
                安全等级
              </Space>
            }
            style={{ borderRadius: '12px', boxShadow: '0 2px 8px rgba(0,0,0,0.1)' }}
          >
            <div style={{ textAlign: 'center', marginBottom: '20px' }}>
              <Progress
                type="circle"
                percent={securityLevel}
                format={percent => `${percent}分`}
                strokeColor={{
                  '0%': '#108ee9',
                  '100%': '#87d068',
                }}
                size={120}
              />
            </div>
            <div style={{ marginBottom: '16px' }}>
              <Text strong>安全建议：</Text>
              <ul style={{ marginTop: '8px', paddingLeft: '20px' }}>
                <li>定期修改密码（建议每3个月）</li>
                <li>使用强密码（包含大小写字母、数字）</li>
                <li>不要在公共场所输入密码</li>
                <li>及时挂失丢失的银行卡</li>
              </ul>
            </div>
          </Card>
        </Col>

        {/* 修改银行卡密码 */}
        <Col xs={24} lg={8}>
          <Card 
            title={
              <Space>
                <CreditCardOutlined style={{ color: '#faad14' }} />
                修改银行卡密码
              </Space>
            }
            style={{ borderRadius: '12px', boxShadow: '0 2px 8px rgba(0,0,0,0.1)' }}
          >
            <Form
              form={cardForm}
              layout="vertical"
              onFinish={handleCardPasswordChange}
            >
              <Form.Item
                name="cardId"
                label="选择银行卡"
                rules={[{ required: true, message: '请选择银行卡' }]}
              >
                <Select placeholder="请选择银行卡">
                  {cards.map(card => (
                    <Option key={card.cardId} value={card.cardId}>
                      {card.cardId}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
              
              <Form.Item
                name="oldPassword"
                label="当前密码"
                rules={[{ required: true, message: '请输入当前密码' }]}
              >
                <Password placeholder="请输入当前密码" />
              </Form.Item>
              
              <Form.Item
                name="newPassword"
                label="新密码"
                rules={[
                  { required: true, message: '请输入新密码' },
                  { min: 6, message: '密码长度至少6位' }
                ]}
              >
                <Password 
                  placeholder="请输入新密码" 
                  onChange={(e) => {
                    const strength = checkPasswordStrength(e.target.value);
                    setSecurityLevel(strength);
                  }}
                />
              </Form.Item>
              
              <Form.Item
                name="confirmPassword"
                label="确认新密码"
                rules={[
                  { required: true, message: '请确认新密码' },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value || getFieldValue('newPassword') === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('两次输入的密码不一致'));
                    },
                  }),
                ]}
              >
                <Password placeholder="请再次输入新密码" />
              </Form.Item>
              
              <Form.Item>
                <Button 
                  type="primary" 
                  htmlType="submit" 
                  loading={loading}
                  icon={<LockOutlined />}
                  style={{ width: '100%' }}
                >
                  修改银行卡密码
                </Button>
              </Form.Item>
            </Form>
          </Card>
        </Col>

        {/* 修改账户密码 */}
        <Col xs={24} lg={8}>
          <Card 
            title={
              <Space>
                <UserOutlined style={{ color: '#722ed1' }} />
                修改账户密码
              </Space>
            }
            style={{ borderRadius: '12px', boxShadow: '0 2px 8px rgba(0,0,0,0.1)' }}
          >
            <Form
              form={userForm}
              layout="vertical"
              onFinish={handleUserPasswordChange}
            >
              <Form.Item
                name="oldPassword"
                label="当前密码"
                rules={[{ required: true, message: '请输入当前密码' }]}
              >
                <Password placeholder="请输入当前账户密码" />
              </Form.Item>
              
              <Form.Item
                name="newPassword"
                label="新密码"
                rules={[
                  { required: true, message: '请输入新密码' },
                  { min: 8, message: '密码长度至少8位' },
                  { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/, message: '密码必须包含大小写字母和数字' }
                ]}
              >
                <Password placeholder="请输入新账户密码" />
              </Form.Item>
              
              <Form.Item
                name="confirmPassword"
                label="确认新密码"
                rules={[
                  { required: true, message: '请确认新密码' },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value || getFieldValue('newPassword') === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('两次输入的密码不一致'));
                    },
                  }),
                ]}
              >
                <Password placeholder="请再次输入新密码" />
              </Form.Item>
              
              <Form.Item>
                <Button 
                  type="primary" 
                  htmlType="submit" 
                  loading={loading}
                  icon={<LockOutlined />}
                  style={{ width: '100%' }}
                >
                  修改账户密码
                </Button>
              </Form.Item>
            </Form>
          </Card>
        </Col>
      </Row>

      {/* 银行卡管理 */}
      <Card 
        title={
          <Space>
            <CreditCardOutlined style={{ color: '#1890ff' }} />
            银行卡管理
          </Space>
        }
        style={{ marginTop: '24px', borderRadius: '12px', boxShadow: '0 2px 8px rgba(0,0,0,0.1)' }}
      >
        <Table
          columns={cardColumns}
          dataSource={cards}
          rowKey="cardId"
          pagination={false}
        />
      </Card>

      {/* 安全提示 */}
      <Card 
        title="安全提示"
        style={{ marginTop: '24px', borderRadius: '12px', boxShadow: '0 2px 8px rgba(0,0,0,0.1)' }}
      >
        <Row gutter={[16, 16]}>
          <Col xs={24} sm={12}>
            <div style={{ display: 'flex', alignItems: 'center', marginBottom: '12px' }}>
              <CheckCircleOutlined style={{ color: '#52c41a', marginRight: '8px' }} />
              <Text strong>安全做法</Text>
            </div>
            <ul style={{ paddingLeft: '20px', color: '#666' }}>
              <li>定期更换密码</li>
              <li>使用不同的密码</li>
              <li>不要在公共场所输入密码</li>
              <li>及时挂失丢失的银行卡</li>
            </ul>
          </Col>
          <Col xs={24} sm={12}>
            <div style={{ display: 'flex', alignItems: 'center', marginBottom: '12px' }}>
              <ExclamationCircleOutlined style={{ color: '#faad14', marginRight: '8px' }} />
              <Text strong>注意事项</Text>
            </div>
            <ul style={{ paddingLeft: '20px', color: '#666' }}>
              <li>不要将密码告诉他人</li>
              <li>不要使用生日等简单密码</li>
              <li>不要在不明网站输入密码</li>
              <li>发现异常及时联系银行</li>
            </ul>
          </Col>
        </Row>
      </Card>
    </PageContainer>
  );
};

export default Security; 